<template>
  <!-- ... existing code ... -->
  <div class="container">
    <div class="top">
      <div class="top_1">
        <span style="font-size: 18px; color: #333"
          >所学课程：{{ showTrainingDetail.name }}</span
        >
        <span
          >课程时长：{{
            (showTrainingDetail.duration / 60).toFixed(1)
          }}小时</span
        >
        <span>课程数量：{{ getCourseCount() }}</span>
        <span>开始时间：{{ formatStartTime }}</span>
        <span>结束时间：{{ formatEndTime }}</span>
      </div>
      <img :src="showTrainingDetail.cover" style="height: 130px" />
    </div>
    <div class="buttom">
      <div class="buttom_top">
        <div
          v-for="(item, index) in tabItems"
          :key="index"
          class="buttom_top_item"
          :class="{ active: activeTab === index }"
          @click="clickHandler(index)"
        >
          {{ item }}
        </div>
      </div>
      <div class="buttom_lower">
        <!-- <span style="display: block; margin-top: 10px" v-if="activeTab === 0">{{
          showTrainingDetail.description
        }}</span> -->
        <div class="buttom_lower_item_description" v-if="activeTab === 0">
          {{ showTrainingDetail.description }}
        </div>
        <div v-if="activeTab === 1">
          <div
            class="buttom_lower_item"
            v-for="(item, index) in pptList"
            :key="item.id"
          >
            <div
              style="
                display: flex;
                justify-content: flex-start;
                align-items: center;
              "
              @click="pptClickHandler(item)"
            >
              <el-icon><Notebook /></el-icon>
              <span style="margin-left: 10px">{{ index + 1 }}.</span>
              <span>{{ item.name }}</span>
            </div>
          </div>
          <div
            class="buttom_lower_item"
            v-for="(item, index) in wordList"
            :key="item.id"
          >
            <div
              style="
                display: flex;
                justify-content: flex-start;
                align-items: center;
              "
              @click="wordClickHandler(item)"
            >
              <el-icon><Document /></el-icon>
              <span style="margin-left: 10px"
                >{{ pptList.length + index + 1 }}.</span
              >
              <span>{{ item.name }}</span>
            </div>
          </div>
          <div
            class="buttom_lower_item"
            style="justify-content: space-between"
            v-for="(item, index) in videoList"
            :key="item.id"
          >
            <div class="buttom_lower_detail" @click="videoClickHandler(item)">
              <el-icon><VideoPlay /></el-icon>
              <span style="margin-left: 10px"
                >{{ pptList.length + wordList.length + index + 1 }}.</span
              >
              <span>{{ item.name }}</span>
            </div>
            <div class="video_progress">
              <div class="buttom_duration">
                {{ getDuration(item.duration) }}
              </div>
              <div class="progress_text" v-if="getVideoProgress(item.url) > 0">
                已学习 {{ getVideoProgress(item.url) }}%
              </div>
            </div>
          </div>
        </div>
        <div class="buttom_lower_item_exam" v-if="activeTab === 2">
          <div
            style="
              flex-direction: column;
              align-items: flex-start;
              justify-content: center;
            "
          >
            <span style="display: block"
              >试卷标题：{{ props.showTrainingDetail.name }}课后试卷</span
            >
            <span style="display: block"
              >试卷数量：{{
                Math.ceil(props.showTrainingDetail.duration / 12)
              }}</span
            >
            <span style="display: block"
              >合格分数：{{ props.showTrainingDetail.passed_score }}</span
            >
            <span style="display: block">最高分数：{{ maxScore }}</span>
            <span style="display: block"
              >考试次数：{{ props.showTrainingDetail.can_test_count }}</span
            >
            <span style="display: block">剩余次数：{{ remainingCount }}</span>
          </div>
          <div
            v-if="maxScore >= props.showTrainingDetail.passed_score"
            style="text-align: center"
          >
            <img style="height: 100px" src="@/assets/success.png" />
            <div style="color: rgb(103, 194, 58); margin-top: 10px">
              考试通过
            </div>
          </div>
          <el-button
            v-else-if="remainingCount > 0"
            icon="Timer"
            style="margin-top: 70px"
            type="primary"
            @click="startExam"
            >开始考试</el-button
          >
          <div v-else style="text-align: center">
            <img style="height: 100px" src="@/assets/error.png" />
            <div style="color: red; margin-top: 10px">考试未通过</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from "vue";
import { useRouter } from "vue-router";
import testApi from "@/api/subject/test";
import store from "@/store";

const router = useRouter();
// 定义组件属性
const props = defineProps({
  showTrainingDetail: {
    type: Object,
    required: true, // 添加必填属性
    default: () => ({}), // 添加默认值
  },
});

// 添加标签页数据和激活状态
// 添加标签页数据和激活状态
const tabItems = computed(() => {
  const baseItems = ["描述", "课程"];
  return props.showTrainingDetail.need_test === 1
    ? [...baseItems, "试卷"]
    : baseItems;
});
const activeTab = ref(0);
const pptList = ref([]);
const videoList = ref([]);
const wordList = ref([]);
const remainingCount = ref(0);
const maxScore = ref(0);

const updateRemainCount = async () => {
  try {
    const res = await testApi.getTestedCountAndScore(
      props.showTrainingDetail.id
    );
    remainingCount.value =
      props.showTrainingDetail.can_test_count - res.data.testedCount;
    maxScore.value = res.data.maxScore;
  } catch (err) {
    remainingCount.value = 0;
  }
};

// 监听 activeTab 变化，当切换到试卷标签时更新剩余次数
watch(activeTab, (newVal) => {
  if (newVal === 2) {
    updateRemainCount();
  }
});

onMounted(() => {
  if (activeTab.value === 2) {
    updateRemainCount();
  }
});

const videoClickHandler = (data) => {
  window.open(
    `/training/video?url=${encodeURIComponent(data.url)}&name=${data.name}&id=${
      props.showTrainingDetail.id
    }`,
    "_blank"
  );
};

import host from "@/utils/host";

const startExam = () => {
  if (store.getters.name) {
    if (flag) {
      testApi
        .startExam(
          props.showTrainingDetail.id,
          Math.ceil(props.showTrainingDetail.duration / 12),
          store.getters.name,
          props.showTrainingDetail.name
        )
        .then((res) => {
          router.push({
            path: "/training/exam",
            query: { type: "subjectTest", questionItemId: res.data },
          });
        });
    } else {
      ElNotification({
        type: "error",
        message: "请学完全部课程！",
        duration: 1500,
      });
    }
  }
};

const wordClickHandler = (data) => {
  // 跳转到专门的 PDF 预览页面
  router.push({
    path: "/training/pdf-viewer",
    query: {
      url: encodeURIComponent(data.url),
      title: data.name,
    },
  });
};

const pptClickHandler = (data) => {
  router.push({
    path: "/training/pdf-viewer",
    query: {
      url: encodeURIComponent(data.url),
      title: data.name,
    },
  });
};

const getDuration = (duration) => {
  const hours = Math.floor(duration / 3600);
  const minutes = Math.floor((duration % 3600) / 60);
  const seconds = duration % 60;

  let result = "";
  if (hours > 0) {
    result += `${hours}小时`;
  }
  if (minutes > 0) {
    result += `${minutes}分`;
  }
  result += `${seconds}秒`;
  return result;
};

const clickHandler = (index) => {
  activeTab.value = index;
  switch (index) {
    case 0:
      break;
    case 1:
      pptList.value = JSON.parse(props.showTrainingDetail.ppt_info);
      videoList.value = JSON.parse(props.showTrainingDetail.video_info);
      wordList.value = JSON.parse(props.showTrainingDetail.word_info);
      break;
    case 2:
      //检查视频是否都已经播放完毕
      const arr = JSON.parse(props.showTrainingDetail.video_info);
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        const url = element.url;
        if (getVideoProgress(url) < 100) {
          flag = false;
          break;
        }
      }
      break;
  }
};

let flag = true;
const getCourseCount = () => {
  if (props.showTrainingDetail.id) {
    const length1 = props.showTrainingDetail.ppt_info
      ? JSON.parse(props.showTrainingDetail.ppt_info).length
      : 0;
    const length2 = props.showTrainingDetail.video_info
      ? JSON.parse(props.showTrainingDetail.video_info).length
      : 0;
    const length3 = props.showTrainingDetail.word_info
      ? JSON.parse(props.showTrainingDetail.word_info).length
      : 0;
    return length1 + length2 + length3;
  }
  return 0;
};

const getVideoProgress = (fileName) => {
  const progress = localStorage.getItem(
    `video-progress-${fileName}-${props.showTrainingDetail.id}`
  );
  return progress ? Math.floor(parseFloat(progress) * 100) : 0;
};

const formatStartTime = computed(() => {
  return props.showTrainingDetail.start_time?.split("T")[0] || "";
});

const formatEndTime = computed(() => {
  return props.showTrainingDetail.end_time?.split("T")[0] || "";
});
</script>

<style scoped>
.container {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.top {
  height: 160px;
  background-color: white;
  width: 100%;
  border-radius: 3px;
  border: 1px solid rgb(226, 226, 226);
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;
  padding: 10px;
}

.top_1 {
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.buttom {
  width: 100%;
  margin-top: 10px;
  background-color: white;
  min-height: 550px;
  height: 100%;
  border-radius: 3px;
  border: 1px solid rgb(226, 226, 226);
}

.buttom_top {
  height: 45px;
  width: 100%;
  background-color: rgb(247, 247, 250);
  border-bottom: 1px solid rgb(226, 226, 226);
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.buttom_top_item {
  height: 45px;
  width: 145px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border-top: 1px solid rgb(226, 226, 226);
  border-bottom: 1px solid rgb(226, 226, 226);
  position: relative; /* 添加相对定位 */
}

.buttom_lower_item_description {
  margin-top: 10px;
}

.buttom_lower_item {
  padding-left: 10px;
  margin-top: 8px;
  height: 55px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  cursor: pointer;
  background-color: rgb(247, 247, 250);
  font-size: 14px;
}

.buttom_lower_item_exam {
  padding-left: 10px;
  padding-right: 10px;
  margin-top: 8px;
  height: 150px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: default;
  background-color: rgb(247, 247, 250);
  font-size: 14px;
}

/* 添加悬浮效果 */
.buttom_lower_item:hover {
  color: rgb(113, 192, 214);
}

.buttom_lower_item:hover .el-icon {
  color: rgb(113, 192, 214);
}

/* 添加激活状态的样式 */
.buttom_top_item.active {
  background-color: white;
  border-bottom: none;
  border-left: 1px solid rgb(226, 226, 226);
  border-right: 1px solid rgb(226, 226, 226);
}

.buttom_top_item:hover {
  color: rgb(113, 192, 214);
}

.buttom_lower {
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  color: black;
  font-family: Arial, Helvetica, sans-serif;
}

.buttom_lower_detail {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.buttom_duration {
  height: 20px;
  width: 120px;
  background-color: rgb(103, 194, 58);
  border-radius: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

.video_progress {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress_text {
  color: #67c23a;
  font-size: 14px;
  white-space: nowrap;
}

span {
  display: flex;
}
</style>
